package agent_store

import (
	"context"
	"encoding/json"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/respx"
	"xialou_platform/app/tools"
	"xialou_platform/services/third_party/rpc/thirdPartyClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type NearbyListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewNearbyListLogic(ctx context.Context, svcCtx *svc.ServiceContext) NearbyListLogic {
	return NearbyListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *NearbyListLogic) NearbyList(req *types.NearStoreListReq) (resp *respx.PageResp, err error) {
	agentId, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return nil, err
	}
	mapNearList, err := l.svcCtx.ThirdPartyRpc.TencentMapNearList(l.ctx, &thirdPartyClient.TencentMapNearListReq{
		Page:     req.Page,
		PageSize: req.PageSize,
		Keyword:  req.Keyword,
		Location: &thirdPartyClient.LocationType{
			Lat: req.Location.Lat,
			Lng: req.Location.Lng,
		},
		City:   req.City,
		AdCode: req.AdCode,
	})
	if err != nil {
		return nil, err
	}

	bytes, err := tools.RequestOtherPlatform(
		l.svcCtx.Config.XiuXianApi.StoreSelect,
		"GET",
		l.svcCtx.Config.Auth.AccessSecret,
		"{}",
		l.svcCtx.Config.Auth.AccessExpire,
		agentId,
	)
	if err != nil {
		return nil, err
	}
	var res StoreSelectResp
	err = json.Unmarshal(bytes, &res)
	if err != nil {
		logx.Infof("调用%v的商家列表接口err：%v", req.Platform, err.Error())
		return nil, errorx.NewMsgReasonCodeError(errorx.DefaultCode, "调用商家列表接口err：%v", err.Error())
	}

	if res.Code != 200 {
		return nil, errorx.NewCodeReason(res.Code, res.Message)
	}

	list := make([]types.NearStoreListResp, 0)
	for _, nearResp := range mapNearList.List {
		var status int64 = 0
		for _, st := range res.Data {
			if st.Name == nearResp.Title {
				status = 2
			}
		}
		temp := types.NearStoreListResp{
			Title:    nearResp.Title,
			Address:  nearResp.Address,
			Category: nearResp.Category,
			Distance: nearResp.Distance,
			Location: types.LocationType{
				Lat: nearResp.Location.Lat,
				Lng: nearResp.Location.Lng,
			},
			Status: status,
			AdInfo: types.AdInfoType{
				Adcode:   nearResp.AdInfo.AdCode,
				Province: nearResp.AdInfo.Province,
				City:     nearResp.AdInfo.City,
				District: nearResp.AdInfo.District,
			},
		}
		list = append(list, temp)
	}

	return respx.NewPageResp(req.Page, req.PageSize, mapNearList.Total, list), nil
}

type StoreSelectResp struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    []struct {
		Id   string `json:"id"`
		Name string `json:"name"`
	} `json:"data"`
}
